<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card>
          <div class="stat-card">
            <div class="stat-title">虚拟机总数</div>
            <div class="stat-value">{{ stats.totalVMs }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <div class="stat-card">
            <div class="stat-title">运行中</div>
            <div class="stat-value" style="color: #67c23a">{{ stats.runningVMs }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <div class="stat-card">
            <div class="stat-title">异常</div>
            <div class="stat-value" style="color: #f56c6c">{{ stats.errorVMs }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <div ref="cpuChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div ref="memoryChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-table :data="alerts" style="width: 100%">
  <el-table-column prop="time" label="时间" width="180">
    <template #default="{row}">
      {{ formatTime(row.timestamp) }}
    </template>
  </el-table-column>
  <el-table-column prop="type" label="类型" width="120">
        <template #default="{row}">
          <el-tag :type="getAlarmTypeTag(row.type)">
            {{ row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="row.status === 'processed' ? 'success' : 'danger'">
            {{ row.status === 'processed' ? '已处理' : '未处理' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{row}">
          <el-button 
            v-if="row.status === 'unprocessed'"
            size="small" 
            type="primary" 
            @click="handleProcessAlarm(row.id)"
          >
            标记为已处理
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增网络监控组件 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <NetworkMonitor />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { ElMessage, ElNotification } from 'element-plus'
import NetworkMonitor from './NetworkMonitor.vue'

// 图表引用
const cpuChart = ref(null)
const memoryChart = ref(null)
const alarms = ref([])
const eventSource = ref(null)

// 响应式数据
const stats = ref({
  totalVMs: 0,
  runningVMs: 0,
  errorVMs: 0
})

const alerts = ref([])
const nodes = ref([])

// 报警类型标签样式
const getAlarmTypeTag = (type) => {
  const typeMap = {
    '网络中断': 'danger',
    'CPU过载': 'warning',
    '内存不足': 'warning',
    '磁盘空间不足': 'danger',
    '服务异常': 'danger'
  }
  return typeMap[type] || 'info'
}

// 定时器引用
let pollInterval = null

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })
}

// 初始化图表
const initCharts = () => {
  if (!nodes.value.length) {
    ElMessage.warning('暂无节点数据，无法绘制图表')
    return
  }

  const cpuChartInstance = echarts.init(cpuChart.value)
  cpuChartInstance.setOption({
    title: { text: 'CPU使用率监控', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: nodes.value.map(node => node.name)
    },
    yAxis: { type: 'value', max: 100 },
    series: [{
      data: nodes.value.map(node => node.cpuUsage || 0),
      type: 'bar',
      itemStyle: {
        color: function(params) {
          const colorList = params.value > 80 ? ['#f56c6c', '#f56c6c'] : 
                          params.value > 60 ? ['#e6a23c', '#e6a23c'] : ['#67c23a', '#67c23a']
          return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: colorList[0] },
            { offset: 1, color: colorList[1] }
          ])
        }
      }
    }]
  })

  const memoryChartInstance = echarts.init(memoryChart.value)
  memoryChartInstance.setOption({
    title: { text: '内存使用率监控', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: nodes.value.map(node => node.name)
    },
    yAxis: { type: 'value', max: 100 },
    series: [{
      data: nodes.value.map(node => node.memoryUsage || 0),
      type: 'bar',
      itemStyle: {
        color: function(params) {
          const colorList = params.value > 80 ? ['#f56c6c', '#f56c6c'] : 
                          params.value > 60 ? ['#e6a23c', '#e6a23c'] : ['#67c23a', '#67c23a']
          return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: colorList[0] },
            { offset: 1, color: colorList[1] }
          ])
        }
      }
    }]
  })

  window.addEventListener('resize', function() {
    cpuChartInstance.resize()
    memoryChartInstance.resize()
  })
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const [vmsRes, nodesRes, alarmsRes] = await Promise.all([
      request.get('/api/vms'),
      request.get('/api/nodes'),
      request.get('/api/alarms')
    ])

    // 健壮性检查
    nodes.value = (nodesRes.data?.items || []).filter(node => node && node.name && typeof node.cpuUsage === 'number' && typeof node.memoryUsage === 'number')
    alerts.value = (alarmsRes.data?.items || []).filter(alarm => alarm && alarm.id)
    const vms = (vmsRes.data?.items || []).filter(vm => vm && vm.id)

    if (!nodesRes.data?.items) {
      console.warn('节点数据格式异常:', nodesRes.data)
      ElMessage.error('节点数据格式错误，请检查后端 /api/nodes 接口')
    }

    stats.value = {
      totalVMs: vms.length,
      runningVMs: vms.filter(vm => vm.status === 'running').length,
      errorVMs: vms.filter(vm => vm.status === 'error').length || 0
    }

    initCharts()
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(error.response?.data?.message || '获取数据失败，请检查后端服务')
  }
}

// 定时轮询节点数据
const startPolling = () => {
  pollInterval = setInterval(async () => {
    try {
      const nodesRes = await request.get('/api/nodes')
      nodes.value = (nodesRes.data?.items || []).filter(node => node && node.name && typeof node.cpuUsage === 'number' && typeof node.memoryUsage === 'number')
      if (!nodesRes.data?.items) {
        console.warn('轮询节点数据格式异常:', nodesRes.data)
      }
      initCharts()
    } catch (error) {
      console.error('轮询节点数据失败:', error)
    }
  }, 60000) // 每分钟更新
}

// 初始化报警流
const initAlarmStream = () => {
  // 关闭现有连接（如果存在）
  if (eventSource.value) {
    eventSource.value.close()
  }

  // 创建新的EventSource连接
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000'
  eventSource.value = new EventSource(`${apiBaseUrl}/stream/alarms`)

  // 消息处理
  eventSource.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      
      if (data.type === 'alarm') {
        // 更新或添加报警
        const index = alarms.value.findIndex(a => a.id === data.data.id)
        if (index >= 0) {
          alarms.value[index] = data.data
        } else {
          alarms.value.unshift({
            ...data.data,
            // 确保时间戳格式统一
            timestamp: data.data.timestamp || Date.now()
          })
        }
        
        // 保持最多100条报警
        if (alarms.value.length > 100) {
          alarms.value.pop()
        }
        
        // 如果是未处理的新报警，显示通知
        if (data.data.status === 'unprocessed') {
          ElNotification({
            title: `新报警 - ${data.data.type}`,
            message: `${data.data.content} (节点: ${data.data.node || '未知'})`,
            type: 'warning',
            duration: 5000,
            position: 'bottom-right'
          })
        }
      } else if (data.type === 'error') {
        ElMessage.error(`报警系统错误: ${data.content}`)
      }
    } catch (e) {
      console.error('处理报警数据失败:', e)
      ElMessage.error('处理报警数据失败，请检查数据格式')
    }
  }
  
  // 错误处理
  eventSource.value.onerror = (e) => {
    if (e.eventPhase === EventSource.CLOSED) {
      ElMessage.warning('报警连接已关闭，尝试重新连接...')
    } else {
      console.error('报警流错误:', e)
      ElMessage.error('报警连接发生错误')
    }
    
    // 5秒后尝试重新连接
    setTimeout(initAlarmStream, 5000)
  }
}
// 处理告警
const handleProcessAlarm = async (alarmId) => {
  try {
    const res = await request.put(`/api/alarms/${alarmId}/status`, { status: 'processed' })
    if (res.status === 'success') {
      ElMessage.success(res.message || '告警已标记为已处理')
      
      // 更新本地状态
      const index = alarms.value.findIndex(a => a.id === alarmId)
      if (index >= 0) {
        alarms.value[index].status = 'processed'
      }
    } else {
      ElMessage.error(res.message || '处理告警失败')
    }
  } catch (error) {
    console.error('处理告警失败:', error)
    ElMessage.error(error.response?.data?.message || '处理告警失败')
  }
}

// 生命周期钩子
onMounted(() => {
  initAlarmStream()
  fetchStats()
  startPolling()
})

onUnmounted(() => {
  if (eventSource.value) {
    eventSource.value.close()
  }
})

onUnmounted(() => {
  if (pollInterval) clearInterval(pollInterval)
  window.removeEventListener('resize', () => {})
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px 0;
}

.stat-title {
  font-size: 16px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.alert-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}
</style>